<?php
namespace Api\Controller;
use Common\Model\EditorModel;
use Common\Model\HouseWorkModel;
use Common\Model\UserModel;
use Common\Model\UtilsModel;
use Common\Model\WeixinModel;
use Think\Controller;
class IndexController extends Controller {
    const SUCCESS   =0;//成功
    const FAILURE   =1;//失败
    public function index(){
        $this->show('星悦，公共支持','utf-8');
    }


    /**
     * 获取行政区划
     * Author: wwl
     * get 方式传递，ID，上次行政区划
     */
    public function getRegion(){
        $provinceID = I('get.id',0,'int');  //省级
        $parentID = I('get.p_id',0,'int');  //上一级id
        $level = I('get.level',1,'int');    //所求数据等级
        $data = array(
            'status' => self::SUCCESS,
        );
        if($level < 5 && $provinceID > 0){
            $regionKv = include_once(WEB_ROOT.'/data/area_info/'.$provinceID.'.php');
            foreach ($regionKv as $key => $val){
                if($val['level'] == $level && $val['p_id'] == $parentID){
                    $data['data'][$key] = $val['name'];
                }
            }
        }
        $this->ajaxReturn($data,'json');
    }

    /**
     * 获取资讯相关联内容
     * Author: shijy
     */
    public function getRelate(){
        $type = I('get.type', 0, 'int');
        switch($type){
            case OBJ_TYPE_ACTIVITY:
                $kv = getEventsKv();
                break;
            case OBJ_TYPE_SHOP:
                $kv = getShopKv();
                break;
            case OBJ_TYPE_POINTMALL:
                $kv = getMallKv();
                break;
            case OBJ_TYPE_ARTICLE:
                $kv = getArticleKv();
                break;
            case OBJ_TYPE_HOUSEWORK:
                $kv = HouseWorkModel::getEnableItemKv();
                break;
        }

        $data=array(
            'status'=>self::SUCCESS,
            'data'=>$kv
        );
        $this->ajaxReturn($data,'json');
    }

    /**
     * 获取商户对应门店数据
     * Author:wwl
     */
    public function getRSRelated(){
        $restaurantId = I('get.restaurantId',0,'int');
        $kv = getShopKv($restaurantId);
        $data=array(
            'status'=>self::SUCCESS,
            'data'=>$kv
        );
        $this->ajaxReturn($data,'json');
    }

    /**
     * 根据文章类型获取达人昵称
     * author:wwl
     */
    public function getDaRenNickname(){
        $contentType = I('get.type',0,'int');
        $contentName = M('cfg_content_type',null,DB_MAIN_CFG)->where("id={$contentType}")->getField("name");
        $daRenType = EditorModel::getDaRenTag();
        $info = M('u_user_base',null,DB_MAIN_CFG)->where("userTag=".$daRenType[$contentName])->field("uid,nickname")->select();
        $kv=array();
        foreach($info as $p){
            $kv[$p['uid']]=$p['nickname'];
        }
        unset($info);
        $this->ajaxReturn($kv);
    }

    /**
     * 获取用户信息
     * Author: shijy
     * get 方式传递，uid,用户编号
     */
    public function getUser(){
        $uid=I('get.uid',0,'int');
        $data=array(
            'status'=>self::SUCCESS
        );
        if($uid==0){
            $data['status']=self::FAILURE;
            $this->ajaxReturn($data,'json');
        }

        $userM=M('u_user_base',null,DB_MAIN_CFG);
        $uinfo=$userM->where("uid={$uid}")->find();
        if(!$uinfo){
            $data['status']=self::FAILURE;
        }else{
            $vipKv=getVipKv();
            $uinfo['vip']=$vipKv[$uinfo['vip']];

            $cfgSexArr=UserModel::getUserSex();//C('USER_SEX');
            $uinfo['sex']=$cfgSexArr[$uinfo['sex']];
            $cfgUserStatus=UserModel::getUserStatus();
            $uinfo['userStatus']=$cfgUserStatus[$uinfo['userStatus']];
            $uinfo['WX_attentionTime']=!$uinfo['WX_attentionTime']?'无':date('Y-m-d  H:i:s',$uinfo['WX_attentionTime']);
            $uinfo['regTime']=!$uinfo['regTime']?'无':date('Y-m-d  H:i:s',$uinfo['regTime']);
            $uinfo['lastLoginTime']=!$uinfo['lastLoginTime']?'无':date('Y-m-d  H:i:s',$uinfo['lastLoginTime']);

            $regionKv=getRegionKv();
            $regionKv_p=getRegionKv($uinfo['province']);
            $regionKv_c=getRegionKv($uinfo['city']);
            $uinfo['address']=$regionKv[$uinfo['province']]
                .'.'.$regionKv_p[$uinfo['city']]
                .'.'.$regionKv_c[$uinfo['district']]
                .'.'.$uinfo['address'];

            $data['data']=$uinfo;
        }
        $this->ajaxReturn($data,'json');
    }


    /**
     * excel 文件ajax上传
     */
    public function ajaxUploadExcel(){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728 ;// 设置附件上传大小 3*1024*1024 3M
        $upload->exts = array('xlsx','xls');// 设置附件上传类型
        $upload->rootPath = '.'.C('FILE_UPLOAD_DIR'); // 设置附件上传根目录
        $upload->savePath = 'excel/';

        $return=array('id'=>0,'msg'=>'');
        // 上传单个文件
        $info = $upload->uploadOne($_FILES['file']);
        if(!$info) {// 上传错误提示错误信息
            $return['msg']=$upload->getError();
        }else{// 上传成功 获取上传文件信息
            $fullPath   = C('FILE_UPLOAD_DIR').$info['savepath'].$info['savename'];
            //id没有实际性意义 只是为了让前台显示
            $return= array('id'=>AJAX_SUCCESS,'msg'=>$fullPath);
        }
        $this->ajaxReturn($return);
    }

    public function ajaxUpload(){
        $from = I('get.from');

        $res = UtilsModel::imageUpload('file',C('FILE_UPLOAD_DIR'));

        if($from && $res['id'] != 0){
            $fromArr = explode(',',$from);
            foreach($fromArr as $key => $val){
                $result[$key] = image_resize($res['msg'],$val);
            }
            $this->ajaxReturn($result[0]);
        } else{
            $this->ajaxReturn($res);
        }
    }
    
    
    
    public  function ajaxUploadArr(){
        $from = I('get.from');

        $res = UtilsModel::imageUploadArr('file',C('FILE_UPLOAD_DIR'));

        if($from && $res['status'] == 0){
            foreach($res['data'] as $key => $val){
                $ret= image_resize($val['path'],$from);
                if($ret['id']==0){
                    $res['data'][$key]['id'] = 0;
                }
                $res['data'][$key]['path'] = $ret['msg'];
            }
        }
            $this->ajaxReturn($res);

    }

    /**
     * EditorUploadImage | 编辑器图片上传
     * User: Rick.Sun.<sunwgjj@126.com>
     * Return: bool|int
     * Address: 浙江宣逸网络科技有限公司
     * @return bool|int
     */
    function editorUploadImage()
    {
        $tmpfile = $_FILES['upfile']['tmp_name'];
        $blob = file_get_contents($tmpfile);

        $temp = array(1=>'.gif', 2=>'.jpeg', 3=>'.png');
        $extName = $temp[getimagesizefromstring($blob)[2]];
        $url = UtilsModel::UploadImage($blob,C('FILE_UPLOAD_DIR'),$extName);

        if($extName == '.gif') {
            return print(json_encode(array(
                'state' => 'SUCCESS',
                'url' => $url,
                'title' => htmlspecialchars($_POST['pictitle'], ENT_QUOTES),
                'original' => htmlspecialchars($_FILES['upfile']['name'], ENT_QUOTES)
            )));
        } else {
            $res=image_resize($url,"IMG_UEDITOR_UPLOAD");

            if($res['id'] >0){
                return print(json_encode(array(
                    'state' => 'SUCCESS',
                    'url' => $res['msg'],
                    'title' => htmlspecialchars($_POST['pictitle'], ENT_QUOTES),
                    'original' => htmlspecialchars($_FILES['upfile']['name'], ENT_QUOTES)
                )));
            } else{
                return print(json_encode(array(
                    'state' => $res['msg'],
                    'url' => $url,
                    'title' => htmlspecialchars($_POST['pictitle'], ENT_QUOTES),
                    'original' => htmlspecialchars($_FILES['upfile']['name'], ENT_QUOTES)
                )));
            }
        }


    }

    // base64图片上传
    public function base64upload() {
        $dataURL = $_POST['dataURL'];
        list($mime, $data) = explode(',', $dataURL);
        $blob = base64_decode($data);
        $mime_array = explode(';', $mime);
        $mime_array = $mime_array[0];
        $extName=explode('/', $mime_array);
        $extName = $extName[1];

        $savePath=C('FILE_UPLOAD_DIR');
        $result = UtilsModel::UploadImage($blob,$savePath,$extName);
        $from = null;//I('get.from');//暂不启动服务端裁图

        if($from && $result){
            //生成对应规格缩略图
            $res = image_resize($result,$from);
            if($res['id'] != 0){
                return print(json_encode(array('status' => 0, 'url' => $res['msg'])));
            } else{
                return print(json_encode(array('status' => 1, 'msg' =>$res['msg'])));
            }

        }
        else if ($result) {
            return print(json_encode(array('status' => 0, 'url' => $result)));
        } else{
            return print(json_encode(array('status' => 1, 'msg' => "图片上传失败，请重试…")));
        }

    }



}